{% load i18n static simpletags %}
<!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
<div id="home">
    <!-- 2. 新增：笑话展示区域（关键！） -->
    <el-card class="mb-4">
        <div slot="header" class="clearfix">
            <i class="fa fa-smile-o"></i>
            <span ></span>  <!-- 国际化文本 -->
            <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="getNewJoke()">  <!-- 刷新笑话按钮 -->
                <i class="fa fa-refresh"></i>
                <span v-text="getLanuage('Refresh')"></span>
            </el-button>
        </div>
        <!-- 笑话内容容器（初始显示加载中，获取成功后替换） -->
        <div id="joke-container" class="p-4 text-center text-gray-600">
            <i class="fa fa-spinner fa-spin"></i>
            <span >...</span>
        </div>
    </el-card>
    <el-card>
            <div class="h-80">
                <canvas id="lineChart"></canvas>
            </div>
    </el-card>


    <el-row class="info-card">

        {% if "SIMPLEUI_HOME_QUICK"|get_config != False%}

        {% if "SIMPLEUI_HOME_INFO"|get_config != False %}
        <el-col :span="18">
            {% else %}
            <el-col :span="24">
                {% endif %}

                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <i class="fas fa-link"></i>
                        <span v-text="getLanuage('Quick navigation')"></span>
                    </div>
                    <div class="clearfix">
                        {% if "SIMPLEUI_HOME_QUICK"|get_config != False %}


                        <div v-for="(c,j) in models" :key="c.name" class="quick-wrap">
                            <a href="javascript:;" @click="openTab(c,(j+1)+'')">
                                <span class="icon" :class="c.icon"></span>
                                <span class="card-name" v-text="c.name"></span>
                            </a>
                        </div>

                        {% endif %}
                    </div>
                </el-card>
            </el-col>
            {% endif %}

            {% if "SIMPLEUI_HOME_INFO"|get_config != False %}
            <el-col :span="6">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">

                        <span><i class="fab fa-stripe-s"></i>Simpleui <span
                                v-text="getLanuage('Home page')"></span></span>
                        <el-button style="float: right; padding: 3px 0" type="text" @click="report()"><span
                                v-text="getLanuage('Report issue')"></span></el-button>
                    </div>
                    <div class="float-wrap clearfix">
                        <div style="text-align: center">
                            {% get_app_info %}
                            <a v-if="upgrade.isUpdate" href="javascript:;" @click="upgrade.dialogVisible=true"
                               class="upgrade"><span class="el-icon-top"></span><span
                                    v-text="upgrade.version"></span></a>
                        </div>
                        <el-button icon="fas fa-code" @click="openUrl('https://gitee.com/tompeppa/simpleui')">Gitee
                        </el-button>
                        <el-button icon="fab fa-github" @click="openUrl('https://github.com/newpanjing/simpleui')">
                            Github
                        </el-button>
                    </div>
                </el-card>
            </el-col>

            {% endif %}
    </el-row>


    {% if "SIMPLEUI_HOME_ACTION"|get_config != False %}
    <el-card class="timeline">
        <div slot="header" class="clearfix">
            <span>{% trans 'Recent actions' %}</span>
            <el-button v-waves style="float: right; padding: 3px 0" type="text"
                       :icon="timeline?'el-icon-arrow-up':'el-icon-arrow-down'"
                       @click="displayTimeline()"></el-button>
        </div>
        {% load log %}
        {% get_admin_log 10 as admin_log for_user user %}
        {% if admin_log %}
        <transition name="el-zoom-in-top">
            <div class="block" v-if="timeline">
                <el-timeline>
                    {% for entry in admin_log %}
                    <el-timeline-item timestamp="{{ entry.action_time }}" placement="top">
                        <el-card>
                            <p>{{ entry.user }} {{ entry.action_time }}</p>
                            <h4 v-pre="true">{{ entry.content_type }}: {{ entry }}</h4>
                        </el-card>
                    </el-timeline-item>
                    {% endfor %}
                </el-timeline>
            </div>
        </transition>
        {% endif %}
    </el-card>
    {% endif %}
</div>

<el-dialog
        title="Upgrade Simpleui"
        :visible.sync="upgrade.dialogVisible"
        width="50%">
    <el-alert
            :title="'You can upgrade to '+upgrade.version"
            type="success">
    </el-alert>
    <div style="padding: 10px">
        <div>
            <h3>
            Run Command:
            </h3>
            <el-alert
                title="pip install django-simpleui -U"
                type="info">
              </el-alert>

        </div>
        <div><h3>Change logs:</h3></div>
        <div v-text="upgrade.body"></div>
    </div>
</el-dialog>


 <script>
        // 页面加载完成后初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            // 获取canvas元素
            const ctx = document.getElementById('lineChart').getContext('2d');

            // 从Django视图获取数据
            {#const labels = {{ labels|safe }};            #}
            {#const data = {{ data|safe }};#}
            {#const yLabel = "{{ y_label }}";#}
            const labels = ['1','2','3' ]
            const data =['10','9','8']
            const yLabel ='趋势图'
            // 创建图表
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: yLabel,
                        data: data,
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(54, 162, 235, 1)',
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        tension: 0.3, // 曲线的平滑度
                        fill: true // 是否填充曲线下方区域
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            titleColor: '#333',
                            bodyColor: '#666',
                            borderColor: '#ddd',
                            borderWidth: 1,
                            padding: 12,
                            boxPadding: 6,
                            usePointStyle: true,
                            callbacks: {
                                label: function(context) {
                                    return `${context.dataset.label}: ${context.raw}`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: yLabel
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });

            // 页面加载完成后，自动获取第一条笑话
            getNewJoke();

        });
        // -------------- 2. 新增：调用笑话API的核心函数 --------------
/**
 * 获取随机笑话（支持页面加载时自动调用、点击刷新按钮调用）
 */
function getNewJoke() {
    // 1. 获取笑话展示容器，显示“加载中”状态
    const jokeContainer = document.getElementById('joke-container');
    jokeContainer.innerHTML = `
        <i class="fa fa-spinner fa-spin"></i>
        <span>..</span>  <!-- 国际化加载文本 -->
    `;

    // 2. 调用公开笑话API（以“笑话大全”为例，支持跨域）
    fetch('https://api.apiopen.top/api/sentences')
        .then(response => {
            // 检查API响应是否成功
            if (!response.ok) {
                throw new Error('Failed to get joke');
            }
            return response.json(); // 解析JSON响应
        })
        .then(data => {
            // 3. 处理API返回的笑话数据（格式：{code: 200, result: [{content: "笑话内容"}]}）
            if (data.code === 200 && data.result) {
                const jokeContent = data.result; // 提取笑话文本
                // 更新容器内容，展示笑话（支持换行，用<br>替换\n）
                jokeContainer.innerHTML = `
                    <p class="text-left whitespace-pre-line">${jokeContent.name.replace(/\n/g, '<br>')}-${jokeContent.from.replace(/\n/g, '<br>')}</p>
                `;
            } else {
                // API返回无数据时的提示
                jokeContainer.innerHTML = `
                    <i class="fa fa-exclamation-circle text-orange-500"></i>
                    <span>${getLanuage('No joke found, try again later')}</span>
                `;
            }
        })
        .catch(error => {
            // 4. 捕获错误（如网络错误、API不可用）
            console.error('Joke API error:', error);
            jokeContainer.innerHTML = `
                <i class="fa fa-times-circle text-red-500"></i>
                <span>${getLanuage('Failed to load joke, check network')}</span>
            `;
        });
}

    </script>